package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

/**
 * @Title: autoGetUserInfo* @Description: 定时调用，将客户信息表中的数据汇总至customer中
 * @author: tian @date 2021-12-28 14:00:00
 */

class autoSMSTemplate implements CallBackInvoke {
    private static final Log log = LogFactory.getLog(autoSMSTemplate.class);

    public void doCallBack(EliteBean eliteBean, String callBack, Map map, String body) {


        try {
            JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());
            // 获取发送所需要的Token
            String DOMAIN = KHDBConfig.getAPIURL(eliteBean, "EliteInner-API")
            JSONObject apiTokenJson = JSONObject.fromObject(Util.doHttpGet(DOMAIN + "/apiGetToken?appid=SMS", "UTF-8", 5000, 0));
            String access_token = apiTokenJson.getJSONObject("data").getString("access_token");
            // 调用地址
            String sendURL = KHDBConfig.getAPIURL(eliteBean, "PA-SMS-templateUrl") + "/" + KHDBConfig.getParam(eliteBean, "SMS-SI") + "?access_token=" + access_token + "&request_id=" + String.valueOf(System.currentTimeMillis());
            // 处理头文件
            Map<String, String> headerMap = new HashMap<String, String>();
            headerMap.put("Accept", "application/json");
            headerMap.put("Content-Type", "application/json");

            String postResult = Util.doHttpGetUseHead(sendURL, "UTF-8", 120000, 0, headerMap);
            log.debug("返回请求体：" + postResult);

            JSONObject resultJson = JSONObject.fromObject(postResult);

            if (resultJson.getString("ret").equals("0")) {
                JSONArray resultArr = resultJson.getJSONObject("data").getJSONArray("result");
                for (int i = 0; i < resultArr.size(); i++) {

                    String templateID = resultArr.getJSONObject(i).getString("templateID");
                    String templateName = resultArr.getJSONObject(i).getString("templateName");
                    String templateContent = resultArr.getJSONObject(i).getString("templateContent");
                    String status = resultArr.getJSONObject(i).getString("status");
                    JSONArray varsList = resultArr.getJSONObject(i).getJSONArray("varsList");
                    log.debug("处理变量Arr:" + varsList.toString());

                    // 处理变量参数
                    String varsListCha = "";
                    for (int j = 0; j < varsList.size(); j++) {
                        if (KHUtil.isNull(varsListCha)) {
                            varsListCha = varsList.getJSONObject(j).getString("variableName");
                        } else {
                            varsListCha = varsListCha + "," + varsList.getJSONObject(j).getString("variableName");
                        }
                    }
                    log.debug("处理变量参数:" + varsListCha);

                    String dealSQL = "select * from Doctemplate where Doctemplate_Id = ?";
                    List<Map<String, Object>> selectCus = jt.queryForList(dealSQL, templateID);

                    log.debug("selectCus：" + selectCus);
                    log.debug("检查数据(" + templateID + ") 数量：" + selectCus.size());

                    if (selectCus.size() == 0) {
                        String insertSQL = "Insert Into Doctemplate (Doctemplate_Id, Docgroup_Id, Description, Documentpath, Documentpath2, Status, Mailmerge, Doctype, Printtype, Type, Doctemplate2, Isparameter, Createrby, Creatertime, Modifiedby, Modifiedtime) Values (?, '', ?, ?, ?, ?, 0, 0, '', '1', ?, '0', 'SELITE', Now(), 'SELITE', Now())";
                        int num = jt.update(insertSQL, templateID, templateName, templateContent, varsList.toString(), status, varsListCha);
                        log.debug("新增数据(" + templateID + ") 数量：" + num);
                    } else {
                        String updateSQL = "Update Doctemplate Set Description = ?, Documentpath = ?, Documentpath2 = ?, Status = ?, Doctemplate2 = ?, Modifiedby = 'SELITE', Modifiedtime = Now() Where Doctemplate_Id = ?";
                        int num = jt.update(updateSQL, templateName, templateContent, varsList.toString(), status, varsListCha, templateID);
                        log.debug("更新数据(" + templateID + ") 数量：" + num);
                    }

                }

            } else {
                log.warn("自动获取短信平台模板失败：" + postResult);
            }

        } catch (Exception e) {
            log.error("自动获取短信平台模板异常-:" + e.getMessage());
        }
    }
}